<!--
 * @Author: 郝奔 1425466221@qq.com
 * @Date: 2024-11-22 09:21:08
 * @LastEditors: 郝奔 1425466221@qq.com
 * @LastEditTime: 2024-12-27 11:14:38
 * @FilePath: /HG-dqbasic_open_platform/src/framework/views/layouts/IframePageView.vue
 * @Description: 
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->

<template>
  <div>
    <iframe ref="designIframe" title="" class="iframe_body" :src="realUrl" frameborder="0" width="100%" height="800px"
      scrolling="auto" />
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  onMounted,
  getCurrentInstance,
  nextTick,
  ComponentInternalInstance
} from 'vue';
import { useTagsViewStore } from '@/framework/store/modules/tagsView';
import { useRouter, useRoute } from "vue-router";
import { isExternal } from '@/framework/utils/validate'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const tagsViewStore = useTagsViewStore();
const props = defineProps({
  url: {
    type: String,
    default: ''
  }
})
const designIframe = ref<HTMLIFrameElement | null>(null);
const router = useRouter();
const route = useRoute();
const realUrl = computed(() => {
  // return 'http://localhost:8100/'
  // 外部链接
  if (isExternal(props.url)) {
    return props.url
  } else { // 内部链接 必须以/开头
    return `${import.meta.env.VITE_APP_TARGET}${props.url}`
  }
})
onMounted(() => {
  // if (route.query.path) {
  //   window.addEventListener('message', handleMessage)
  // }
  const id = route.query.id

  nextTick(() => {
    // 获取iframe元素
    // const iframe = document.getElementById('designIframe')
    if (designIframe.value) {
      const iframe = designIframe.value
      iframe.onload = function (): void {
        // 通过.contentWindow.postMessage(data,"*")向iframe子组件传值
        const content = iframe.contentWindow
        if (id) {
          content && content.postMessage({
            cmd: 'editPage',
            params: {
              id
            }
          }, '*')
        } else {
          content && content.postMessage({
            cmd: 'addPage'
          }, '*')
        }
      }
    }
  })

})
function handleMessage(event: { data: { cmd: string; params: { showMessage: string } }; }): void {
  const data = event.data
  console.log("data", data)
  if (data.cmd === 'closePage') {
    // console.log('返回流程设计', this.$route.query.path)
    // this.$router.go(-1)
    // this.$router.replace(this.$route.query.path)
    const nowtag = tagsViewStore.visitedViews.filter(item => {
      if (item.path === route.path) return item
    })
    tagsViewStore.delView(nowtag[0])
    router.go(-1)
    if (data.params.showMessage) {
      proxy?.$modal.msgSuccess(route.query.id ? '修改成功' : '创建成功')
    }
  }
}
onBeforeUnmount(() => {
  window.removeEventListener('message', handleMessage)
}) 
</script>

<style lang="scss" scoped>
.iframe_body {
  padding: 10px;
  background: #fff;
}
</style>
